package com.zhuozhou.jdyc.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.zhuozhou.jdyc.api.UserAccountHelper;
import com.zhuozhou.jdyc.main.base.activity.PermissionsActivity;
import com.zhuozhou.jdyc.main.user.activity.LoginActivity;
import com.zhuozhou.jdyc.util.apiUtil.StringUtil;
import com.zhuozhou.jdyc.util.log.ToastUtils;
import com.zhuozhou.jdyc.util.permission.PermissionsChecker;
import com.zhuozhou.jdyc.wight.dialog.CustomProgressDialog;
import com.zhuozhou.jdyc.wight.dialog.LoginDialog;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Objects;

/**
 * Created by 方舟 on 2017/11/22.
 * BaseFragment封装
 */

public abstract class BaseFragment<VM extends BaseViewModel, VDB extends ViewDataBinding> extends Fragment implements BaseView, LoginDialog.OnLoginClickListener {
    protected Activity mActivity;
    public LoginDialog loginDialog = null;
    protected CustomProgressDialog customProgressDialog;
    /**
     * 权限检测器
     */
    private PermissionsChecker mPermissionsChecker;
    protected VM mViewModel;
    protected View mContentView;
    protected VDB binding;
    protected Bundle baseBundle;

    /**
     * 获得全局的，防止使用getActivity()为空
     *
     * @param context 视图
     */
    @Override
    public void onAttach(@NotNull Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    @Override
    public void onLoginClick(View v, int code) {
        LoginActivity.show(this, new Bundle(), code);
    }

    public void requestPermission(int reqCode, String[] permissions) {
        if (lacksPermissions(permissions)) {
            PermissionsActivity.startActivityForResult(getActivity(), reqCode, permissions);
        }
    }

    private PermissionsChecker getPermissionsChecker() {
        if (mPermissionsChecker == null) {
            mPermissionsChecker = new PermissionsChecker(Objects.requireNonNull(getActivity()));
        }
        return mPermissionsChecker;
    }

    public boolean lacksPermissions(String[] permissions) {
        return getPermissionsChecker().lacksPermissions(permissions);
    }

    /**
     * 弹出登录dialog
     *
     * @param context     视图
     * @param message     提示文本文字
     * @param requestCode 请求code
     */
    public void showLoginDialog(Activity context, LoginDialog.OnLoginClickListener listener, String message, int requestCode) {
        BaseActivity baseActivity = (BaseActivity) getActivity();
        baseActivity.showLoginDialog(context, listener, message, requestCode);
    }

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        mContentView = binding.getRoot();
        customProgressDialog = new CustomProgressDialog(getActivity());
        createViewModel();
        initView(mContentView, savedInstanceState);
        return mContentView;
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        customProgressDialog.dismiss();
    }

    public void createViewModel() {
        if (mViewModel == null) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
            } else {
                //如果没有指定泛型参数，则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            mViewModel = (VM) new ViewModelProvider(this).get(modelClass);
            mViewModel.setBaseView(createBaseView());
        }
    }

    protected BaseView createBaseView() {
        return this;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData(getArguments() == null ? new Bundle() : getArguments());
        baseBundle = getArguments() == null ? new Bundle() : getArguments();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mViewModel != null) {
            mViewModel.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 该抽象方法就是 onCreateView中需要的layoutID
     *
     * @return 布局资源id
     */
    protected abstract int getLayoutId();

    /**
     * 该抽象方法就是 初始化view
     *
     * @param view               视图view
     * @param savedInstanceState bundle
     */
    protected abstract void initView(View view, Bundle savedInstanceState);

    /**
     * 执行数据的加载
     */
    protected abstract void initData(Bundle bundle);


    public long lastClick = 0;

    /**
     * [防止快速点击]
     *
     * @return true-快速点击
     */
    public boolean fastClick(long intervalTime) {
        if (System.currentTimeMillis() - lastClick <= intervalTime) {
            return true;
        }
        lastClick = System.currentTimeMillis();
        return false;
    }

    /**
     * 关闭弹框
     */
    private void closeLoadingDialog() {
        customProgressDialog.getInstance(getContext()).hide();
    }

    /**
     * 显示加载弹框
     *
     * @param dialogMessage 弹框内容，如果内容为空则不展示文字部分
     */
    private void showLoadingDialog(String dialogMessage, boolean isCanCancel) {
        customProgressDialog.getInstance(getContext())
                .setCanCancel(isCanCancel)
                .isShowBg(StringUtil.isEmpty(dialogMessage))
                .setMessage(dialogMessage)
                .builder()
                .show();
    }

    @Override
    public void showLoading(String dialogMessage) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            getActivity().runOnUiThread(() -> showLoadingDialog(dialogMessage, false));
        }
    }

    @Override
    public void hideLoading() {
        if (getActivity() != null && !getActivity().isFinishing()) {
            getActivity().runOnUiThread(this::closeLoadingDialog);
        }
    }

    @Override
    public void refreshLoading(String dialogMessage) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            getActivity().runOnUiThread(() -> {
                customProgressDialog.getInstance(getActivity())
                        .setMessage(dialogMessage)
                        .builder()
                        .show();
            });
        }
    }

    @Override
    public void showToast(String msg) {
        ToastUtils.showShort(getActivity(), msg);
    }

    @Override
    public void onErrorCode(BaseModelEntity model) {
        if (model != null && (UserAccountHelper.isLoginPast(model.getCode()) || UserAccountHelper.isNoPermission(model.getCode()))) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isShowProjectCode", false);
            LoginActivity.show(this, bundle);
        }
    }

    public void startActivity(Class<?> clx) {
        startActivity(new Intent(getContext(), clx));
    }

    public void startActivity(Class<?> clx, Bundle bundle) {
        Intent intent = new Intent(getContext(), clx);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startActivityForResult(Class<?> clx, int requestCode) {
        startActivityForResult(new Intent(getContext(), clx), requestCode);
    }

    public void startActivityForResult(Class<?> clx, Bundle bundle, int requestCode) {
        Intent intent = new Intent(getContext(), clx);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }
}
